package com.oriental.manage.controller.check;

import com.oriental.check.commons.enums.Status;
import com.oriental.check.commons.util.DateUtil;
import com.oriental.check.service.facade.manager.ChkFileInfoFacade;
import com.oriental.check.service.facade.manager.model.ChkFileInfoDTO;
import com.oriental.manage.core.dfsUtils.FastDFSPoolUtil;
import com.oriental.manage.core.exception.BusiException;
import com.oriental.manage.core.fileUtils.FileUtilsExt;
import com.oriental.manage.core.paging.Pagination;
import com.oriental.manage.core.response.ResponseDTO;
import com.oriental.manage.core.system.log.OperateLogger;
import com.oriental.manage.core.utils.SessionUtils;
import com.oriental.paycenter.commons.mode.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * <ul>
 * <li>对账文件信息控制器</li>
 * <li>User:蒯越 Date:2016/5/11 Time:10:29</li>
 * </ul>
 */
@Slf4j
@Controller
public class ChkFileInfoController {

    @Autowired
    private ChkFileInfoFacade chkFileInfoFacade;

    @Value("#{cfgProperties['downloadTempDir']}")
    private String downloadTempDir;

    @Autowired
    private FastDFSPoolUtil fastDFSPoolUtil;

    @RequestMapping("/check/chkFileInfo/init")
    public String init() {
        return "check/searchChkFileInfo";
    }

    @OperateLogger(content = "对账文件信息查询", operationType = OperateLogger.OperationType.R)
    @ResponseBody
    @RequestMapping("/check/chkFileInfo/search")
    public ResponseDTO<Pagination<ChkFileInfoDTO>> queryPage(Pagination<ChkFileInfoDTO> pagination,
                                                             ChkFileInfoDTO query,
                                                             String sSettleDateStart,
                                                             String sSettleDateEnd) {
        ResponseDTO<Pagination<ChkFileInfoDTO>> responseDTO = new ResponseDTO<Pagination<ChkFileInfoDTO>>();
        try {
            query.setStartRow(pagination.getStartRow());
            query.setPageSize(pagination.getPageSize());
            query.setDateStart(DateUtil.parse(sSettleDateStart));
            query.setDateEnd(DateUtil.parse(sSettleDateEnd));
            Response<com.oriental.check.service.facade.model.Pagination<ChkFileInfoDTO>> response
                    = chkFileInfoFacade.pageQuery(query, SessionUtils.getUserName());
            if (response.isSuccess()) {
                pagination.setRowCount(response.getResult().getTotalCount());
                pagination.setList(response.getResult().getPageList());
                responseDTO.setSuccess(true);
                responseDTO.setObject(pagination);
            } else {
                responseDTO.setSuccess(false);
                responseDTO.setMsg(response.getErrorMsg());
            }
        } catch (BusiException e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("查询失败", e);
            responseDTO.setSuccess(false);
            responseDTO.setMsg("系统繁忙");
        }
        return responseDTO;
    }

    @OperateLogger(content = "对账文件批量下载", operationType = OperateLogger.OperationType.R)
    @RequestMapping("/check/chkFileInfo/batchDownload")
    public ResponseEntity<byte[]> batchDownload(String sSettleDateStart, String sSettleDateEnd) {
        try {
            log.info("对账文件批量下载,请求参数,开始日期【{}】结束日期【{}】", sSettleDateStart, sSettleDateEnd);
            ChkFileInfoDTO query = new ChkFileInfoDTO();
            query.setStartRow(0);
            query.setPageSize(10000);
            query.setDateStart(DateUtil.parse(sSettleDateStart));
            query.setDateEnd(DateUtil.parse(sSettleDateEnd));
            query.setStatus(Status.CHK_FILE_INFO_ORG_DOWNLOAD_SUCCESS.getCode());
            Response<com.oriental.check.service.facade.model.Pagination<ChkFileInfoDTO>> response1
                    = chkFileInfoFacade.pageQuery(query, SessionUtils.getUserName());
            query.setStatus(Status.CHK_FILE_INFO_MCHNT_CREATE_SUCCESS.getCode());
            Response<com.oriental.check.service.facade.model.Pagination<ChkFileInfoDTO>> response2
                    = chkFileInfoFacade.pageQuery(query, SessionUtils.getUserName());
            if (response1.isSuccess() && response2.isSuccess()) {
                String path = downloadTempDir + "/batchChkFile-" + sSettleDateStart + "-" + sSettleDateEnd + "/";
                FileUtilsExt.writeFile(path);
                List<ChkFileInfoDTO> chkFileInfoDTOList1 = response1.getResult().getPageList();
                List<ChkFileInfoDTO> chkFileInfoDTOList2 = response2.getResult().getPageList();
                this.downloadChkFiles(chkFileInfoDTOList1, path);
                this.downloadChkFiles(chkFileInfoDTOList2, path);
                String zipFileName = "batchChkFile-" + sSettleDateStart + "-" + sSettleDateEnd + ".zip";
                String localFileName = downloadTempDir + "/" + zipFileName;
                File[] files = new File(path).listFiles();
                if (files != null) {
                    FileUtilsExt.zipFile(Arrays.asList(files), localFileName);
                }
                FileUtilsExt.deleteDirectory(new File(path));
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", new String(zipFileName.getBytes("UTF-8"), "ISO-8859-1"));
                return new ResponseEntity<>(FileUtils.readFileToByteArray(new File(localFileName)), headers, HttpStatus.CREATED);
            } else {
                log.error("下载失败：原因1【{}】原因2【{}】", response1.getErrorMsg(), response2.getErrorMsg());
            }
        } catch (Exception e) {
            log.error("下载失败：", e);
        }
        return null;
    }

    private void downloadChkFiles(List<ChkFileInfoDTO> chkFileInfoDTOList, String path) {
        if (chkFileInfoDTOList != null && !chkFileInfoDTOList.isEmpty()) {
            for (ChkFileInfoDTO chkFileInfoDTO : chkFileInfoDTOList) {
                fastDFSPoolUtil.download(chkFileInfoDTO.getOriginalDfsGroupName(),
                        chkFileInfoDTO.getOriginalDfsRemoteFilename(),
                        path + chkFileInfoDTO.getCompanyCode() + "_" + chkFileInfoDTO.getLocalFilename());
            }
        }
    }
}
